# -*- coding:utf-8 -*-
__author__ = 'quantum8023'
 
import os,sys
import chardet
import re

def get_current_path():
    paths = sys.path
    current_file = os.path.basename(__file__)
    for path in paths:
        try:
            if current_file in os.listdir(path):
                return path
        except (FileExistsError,FileNotFoundError) as e:
            print(e)

def convert( filename, out_enc="utf-8"):
    try:
        fp = open(filename, 'rb')
        content = fp.read()
        fp.close()
        result = chardet.detect(content)#通过chardet.detect获取当前文件的编码格式串，返回类型为字典类型        
        in_enc = result.get('encoding')#获取encoding的值[编码格式]
        if in_enc != None and in_enc != 'utf-8':#文件格式如果不是utf-8的时候，才进行转码
            print(filename + ": convert from " + in_enc + " to utf-8 ", end="")
            new_content = content.decode(in_enc).encode(out_enc)
            fp = open(filename, 'wb')
            fp.write(new_content)
            fp.close()
            print("done")
    except IOError as e:
    # except:
        print(" error")
 
def explore(dir):
    print("[explore] dir " + dir)
    for root, dirs, files in os.walk(dir, topdown=True):
        for file in files:
            if re.search(r"(\.h|\.c|\.s|\.S)$", file) != None:
                path = os.path.join(root, file)
                convert(path)

def main():
    print("***  Start convert  ***")
    explore(get_current_path())
 
if __name__ == "__main__":
    main()